/**
 * 
 */
package com.googlecode.xcarve.config.provider;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import com.googlecode.xcarve.config.ConfigProvider;
import com.googlecode.xcarve.netty.server.NettyServer;

/**
 * @author duxinyun
 *
 */
public class AbstractServiceProvider extends ConfigProvider implements InitializingBean,DisposableBean{

	private transient final Map<String,NettyServer> serverMap = new ConcurrentHashMap<String, NettyServer>();
	static final Logger logger = LoggerFactory.getLogger(AbstractServiceProvider.class);
	
	public Map<String, NettyServer> getServerMap() {
		return serverMap;
	}
	
	public NettyServer getServerMap(String server) {
		return serverMap.get(server);
	}

	@Override
	public void destroy() throws Exception {
		close();
	}
	
	protected synchronized void close(){
		if(CollectionUtils.isEmpty(serverMap)){
			return;
		}
		
		for(Entry<String, NettyServer> server : serverMap.entrySet()){
			if(!server.getValue().isClosed()){
				server.getValue().close();
			}
		}
	}
	
	void export(){
		setExported(true);
		logger.info("xcarve start to export service.");
		String path = toServicePath();
		getZkInstance().createPath(path, true);
		logger.info("xcarve export service to zookeeper successfull, service={}",path);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if( getInterfaceClass() == null && StringUtils.isBlank(this.getInterfaceName()) ){
			throw new IllegalStateException("interfaceClass or interfaceName is null.");
		}
		if( getInterfaceClass() == null){
			this.setInterfaceClass(Class.forName(getInterfaceName(), true, Thread.currentThread().getContextClassLoader()));
		} 
		if( !getInterfaceClass().isInterface() ){
			throw new IllegalStateException(" this field[interfaceClass] value ="+ getInterfaceClass() +"is not a interface.");
		}
		if( getUser() == null || ( StringUtils.isBlank(getUser().getUsername()) && StringUtils.isBlank(getUser().getUserEmail()) ) ){
			throw new IllegalArgumentException("must set the service user config. username|useremail");
		}
		if( getUser().getIsProvider() == null)
			throw new IllegalArgumentException("service user config field=[isProvider] must be set true|false.");
		if(StringUtils.isBlank(getDomain()))
			throw new IllegalArgumentException("service about config field=[domain] must be set.");
		
	}
}
